package leetcode.code0347;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

import leetcode.IDebug;

public class Solution implements IDebug {

	public int[] topKFrequent(int[] nums, int k) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int num : nums) {
			map.put(num, map.getOrDefault(num, 0) + 1);
		}
		PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
			if (pq.size() < k) {
				pq.add(new int[] { entry.getValue(), entry.getKey() });
			} else {
				if (pq.peek()[0] < entry.getValue()) {
					pq.poll();
					pq.add(new int[] { entry.getValue(), entry.getKey() });
				}
			}
		}
		int[] ans = new int[k];
		for (int i = 0; i < k; i++) {
			ans[i] = pq.poll()[1];
		}
		return ans;
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
